package com.xywl.escort.view.order.subscription

import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_repurchase_dialog.*
import javax.inject.Inject

/**
 * 收购弹框
 */
@Route(path = "/xy/order/repurchase/dialog")
class RepurchaseDialogActivity : BaseActivity(), RepurchaseDialogContract.View {
    @Autowired
    @JvmField
    var projectId = ""

    @Autowired
    @JvmField
    var holdNum = 0

    @Inject
    lateinit var mPresenter: RepurchaseDialogContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_repurchase_dialog)
        ARouter.getInstance().inject(this)

        btn_confirm.setOnClickListener {
            repurchase()
        }

        image_close.setOnClickListener {
            finish()
        }

        pop_reduce.setOnClickListener {
            subNum()
        }
        pop_add.setOnClickListener {
            addNum()
        }
    }

    private fun repurchase() {
        mPresenter.takeView(this)
        val numString = pop_num.text.toString().trim()
        val num = Integer.valueOf(numString)
        mPresenter.repurchase(projectId, num)
    }

    /**
     * 增加数量
     */
    private fun addNum() {
        val strNum = pop_num.text.toString()
        val num = Integer.parseInt(strNum)
        if (holdNum - num > 0) {
            val numAdd = Integer.parseInt(strNum) + 1
            pop_num.text = numAdd.toString()
        } else {
            ToastUtil.showTip(this, "已达到最大发货量")
        }
    }

    /**
     * 减小数量
     */
    private fun subNum() {
        val strNum = pop_num.text.toString()
        if (Integer.parseInt(strNum) > 1) {
            val numReduce = Integer.parseInt(strNum) - 1
            pop_num.text = numReduce.toString()
        } else {
            ToastUtil.showTip(this, "不能再减少了")
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun repurchaseSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "操作成功！！！")
        finish()
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun repurchaseFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }
}
